package com.booking.springrestful.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.booking.springrestful.domain.*;
import com.booking.springrestful.domain.dto.AppointmentsDto;
import com.booking.springrestful.domain.dto.BookingDto;
import com.booking.springrestful.domain.dto.GetCouByUserIdDto;
import com.booking.springrestful.domain.vo.*;
import com.booking.springrestful.mapper.*;
import com.booking.springrestful.resp.PageResult;
import com.booking.springrestful.service.AppointmentsService;
import com.booking.springrestful.utills.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author 13182
* @description 针对表【appointments(来访者的预约表)】的数据库操作Service实现
* @createDate 2024-11-05 20:39:54
*/
@Service
@Slf4j
public class AppointmentsServiceImpl extends ServiceImpl<AppointmentsMapper, Appointments>
    implements AppointmentsService {


    @Resource
    private CounselorsMapper counselorsMapper;

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private CounselorscheduleMapper counselorscheduleMapper;

    @Resource
    private UseranalyticsMapper useranalyticsMapper;


    @Resource
    private AppointmentsMapper appointmentsMapper;

    @Resource
    private UserassessmentsMapper userassessmentsMapper;


    @Resource
    private FeedbackMapper feedbackMapper;


    //预约
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void appointment(AppointmentsDto appointments) {

        //插入预约记录
        appointments.setAppointmenttime(new Date());
        appointments.setStatus(StatusEnum.SCHEDULED);
        appointmentsMapper.insert(appointments);

        //修改时间段状态
        Counselorschedule counselorschedule = new Counselorschedule();
        counselorschedule.setIsavailable(0);
        counselorscheduleMapper.update(counselorschedule,new QueryWrapper<Counselorschedule>().eq("scheduleId",appointments.getScheduleid()));
    }


    //查询咨询师
    @Override
    public List<List<AppointmentVo>> listCou(Counselors counselors) {

        QueryWrapper<Counselors> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(counselors.getSpecialty())) {
            wrapper.eq("specialty", counselors.getSpecialty());
        }

        // 获取顾问列表
        List<Counselors> list = counselorsMapper.selectList(wrapper.eq("status", "1").orderByDesc("rating"));
        List<AppointmentVo> appointmentVos = new ArrayList<AppointmentVo>();

        // 填充 appointmentVos
        list.forEach(item -> {
            AppointmentVo appointmentVo = new AppointmentVo();
            BeanUtils.copyProperties(item, appointmentVo);

            Users one = usersMapper.selectOne(new QueryWrapper<Users>().eq("userId", item.getUserid()));
            appointmentVo.setName(one.getRealname());
            appointmentVo.setAvatar(one.getAvatar());

            boolean exists = useranalyticsMapper.exists(new QueryWrapper<Useranalytics>().eq("counselorId", item.getCounselorid()));
            //Useranalytics useranalytics = useranalyticsMapper.selectOne(new QueryWrapper<Useranalytics>().eq("userId", item.getCounselorid()));
            //log.info(useranalytics.toString());
            if (exists){
                Useranalytics useranalytics = useranalyticsMapper.selectOne(new QueryWrapper<Useranalytics>().eq("counselorId", item.getCounselorid()));
                if (useranalytics.getCompletedappointments()!=null) {
                    appointmentVo.setNumber(useranalytics.getCompletedappointments());
                }else {
                    appointmentVo.setNumber(0);
                }
            }



            List<Counselorschedule> selectList = counselorscheduleMapper.selectList(new QueryWrapper<Counselorschedule>().eq("counselorId", item.getCounselorid()));
            appointmentVo.setCounselorscheduleList(selectList);
            appointmentVos.add(appointmentVo);
        });

        // 将 appointmentVos 分组为每组 4 个元素
        return groupList(appointmentVos, 4);
    }

    @Override
    public PageResult<AppointmentRecordVo> getByUserId(GetCouByUserIdDto dto) {

        Integer counselorid = counselorsMapper.selectOne(new QueryWrapper<Counselors>().eq("userId", dto.getUserid())).getCounselorid();

        long pageSize = dto.getPageSize();
        long current = dto.getCurrent();

        QueryWrapper<Appointments> wrapper = new QueryWrapper<>();
        wrapper.eq("counselorId",counselorid).orderByDesc("appointmentTime");

        IPage<Appointments> page = new Page<>(current, pageSize); // 创建分页对象

        // 进行分页查询
        IPage<Appointments> resultPage = appointmentsMapper.selectPage(page, wrapper);

        IPage<AppointmentRecordVo> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        ArrayList<AppointmentRecordVo> voRecords = new ArrayList<>();

        resultPage.getRecords().forEach(record -> {
            AppointmentRecordVo vo = new AppointmentRecordVo();
            BeanUtils.copyProperties(record, vo);
            Users users = usersMapper.selectOne(new QueryWrapper<Users>().eq("userId", record.getUserid()));
            vo.setName(users.getRealname());
            vo.setPhone(users.getPhone());



            Counselorschedule counselorschedule = counselorscheduleMapper.selectOne(new QueryWrapper<Counselorschedule>().eq("scheduleId", record.getScheduleid()));
            vo.setRoom(counselorschedule.getRoom());
            vo.setStartTime(counselorschedule.getStarttime());
            vo.setEndTime(counselorschedule.getEndtime());
            vo.setWeekend(counselorschedule.getWeekend());

            voRecords.add(vo);
        });

        voPage.setRecords(voRecords);

        // 创建包含数据和分页信息的对象
        PageResult<AppointmentRecordVo> pageResult = new PageResult<>();
        pageResult.setTotal(voPage.getTotal());
        pageResult.setData(voPage.getRecords());

        return pageResult;

    }

    @Override
    public void cancel(AppointmentRecordVo appointmentRecordVo) {
        Integer scheduleid = appointmentRecordVo.getScheduleid();
        Integer appointmentid = appointmentRecordVo.getAppointmentid();
        String remark = appointmentRecordVo.getRemark();

        //填写取消原因并且修改状态
        Appointments appointments = new Appointments();
        appointments.setAppointmentid(appointmentid);
        appointments.setStatus(StatusEnum.CANCELED);
        appointments.setRemark(remark);
        appointmentsMapper.updateById(appointments);

        Counselorschedule counselorschedule = new Counselorschedule();
        counselorschedule.setIsavailable(1);
        counselorschedule.setScheduleid(scheduleid);
        counselorscheduleMapper.updateById(counselorschedule);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void complete(AppointmentRecordVo appointmentRecordVo) {
        //更新预约单状态为已完成
        Appointments appointments = new Appointments();
        appointments.setAppointmentid(appointmentRecordVo.getAppointmentid());
        appointments.setStatus(StatusEnum.COMPLETED);
        appointmentsMapper.updateById(appointments);

        //修改时间段状态
        Counselorschedule counselorschedule = new Counselorschedule();
        counselorschedule.setIsavailable(1);
        counselorschedule.setScheduleid(appointmentRecordVo.getScheduleid());
        counselorscheduleMapper.updateById(counselorschedule);

        //生成评估信息
        Userassessments userassessments = new Userassessments();
        userassessments.setUserid(appointmentRecordVo.getUserid());
        userassessments.setResults(appointmentRecordVo.getResults());
        userassessments.setAppointmentid(appointmentRecordVo.getAppointmentid());
        userassessmentsMapper.insert(userassessments);

    }

    @Override
    public PageResult<AppointmentRecordVo> getCouByUserId(GetCouByUserIdDto dto) {

        long pageSize = dto.getPageSize();
        long current = dto.getCurrent();

        QueryWrapper<Appointments> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", dto.getUserid()).orderByDesc("appointmentTime");

        IPage<Appointments> page = new Page<>(current, pageSize); // 创建分页对象

        // 进行分页查询
        IPage<Appointments> resultPage = appointmentsMapper.selectPage(page, wrapper);


        IPage<AppointmentRecordVo> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        ArrayList<AppointmentRecordVo> voRecords = new ArrayList<>();


        resultPage.getRecords().forEach(record -> {
            // 在循环中处理每条记录，并转换为 AppointmentRecordVo
            AppointmentRecordVo vo = new AppointmentRecordVo();

            BeanUtils.copyProperties(record, vo);
            Integer id = counselorsMapper.selectOne(new QueryWrapper<Counselors>().eq("counselorId",record.getCounselorid())).getUserid();
            Users users = usersMapper.selectOne(new QueryWrapper<Users>().eq("userId", id));
            vo.setName(users.getRealname());
            vo.setPhone(users.getPhone());
            Counselorschedule counselorschedule = counselorscheduleMapper.selectOne(new QueryWrapper<Counselorschedule>().eq("scheduleId", record.getScheduleid()));
            vo.setRoom(counselorschedule.getRoom());
            vo.setStartTime(counselorschedule.getStarttime());
            vo.setEndTime(counselorschedule.getEndtime());
            vo.setWeekend(counselorschedule.getWeekend());
            vo.setStatus(record.getStatus());
            boolean exists = feedbackMapper.exists(new QueryWrapper<Feedback>().eq("appointmentId", record.getAppointmentid()));
            log.info(String.valueOf(exists));
            vo.setIsFeed(exists);

            voRecords.add(vo);
        });

        voPage.setRecords(voRecords);

        // 创建包含数据和分页信息的对象
        PageResult<AppointmentRecordVo> pageResult = new PageResult<>();
        pageResult.setTotal(voPage.getTotal());
        pageResult.setData(voPage.getRecords());

        return pageResult;
    }

    @Override
    public Userassessments getAssess(Integer id) {
        return userassessmentsMapper.selectOne(new QueryWrapper<Userassessments>().eq("appointmentId", id));
    }

    @Override
    public PageResult<BookingVo> getBooking(BookingDto bookingDto) {

        QueryWrapper<Appointments> wrapper = new QueryWrapper<>();

        if (bookingDto.getDateTimeRange() != null){
            Date start= bookingDto.getDateTimeRange().get(0);
            Date end= bookingDto.getDateTimeRange().get(1);
            wrapper.between("appointmentTime",start,end);
        }
        wrapper.orderByDesc("createdAt");

        long pageSize = bookingDto.getPageSize();
        long current = bookingDto.getCurrent();

        log.info(String.valueOf(pageSize));
        log.info(String.valueOf(current));

        IPage<Appointments> page = new Page<>(current, pageSize); // 创建分页对象

        // 进行分页查询
        IPage<Appointments> resultPage = appointmentsMapper.selectPage(page, wrapper);

        IPage<BookingVo> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        List<BookingVo> voRecords = new ArrayList<>();

        resultPage.getRecords().forEach(item -> {
            BookingVo bookingVo = new BookingVo();
            BeanUtils.copyProperties(item, bookingVo);

            String user = usersMapper.selectOne(new QueryWrapper<Users>().eq("userId", item.getUserid())).getRealname();
            bookingVo.setUserRealname(user);

            Integer userid = counselorsMapper.selectOne(new QueryWrapper<Counselors>().eq("counselorId", item.getCounselorid())).getUserid();
            String couName = usersMapper.selectOne(new QueryWrapper<Users>().eq("userId", userid)).getRealname();
            bookingVo.setCounselorname(couName);

            Counselorschedule one = counselorscheduleMapper.selectOne(new QueryWrapper<Counselorschedule>().eq("scheduleId", item.getScheduleid()));
            bookingVo.setRoom(one.getRoom());
            bookingVo.setWeekend(one.getWeekend());

            //转换时间为时间段字符串
            Date starttime = one.getStarttime();
            Date endtime = one.getEndtime();

            bookingVo.setTimes(formatTimeRange(starttime,endtime));

            voRecords.add(bookingVo);
        });

        voPage.setRecords(voRecords);

        // 创建包含数据和分页信息的对象
        PageResult<BookingVo> pageResult = new PageResult<>();
        pageResult.setTotal(voPage.getTotal());
        pageResult.setData(voPage.getRecords());
        return pageResult;
    }

    @Override
    public List<BookingTimesVo> bookingTimes() {
        List<Appointments> appointments = appointmentsMapper.selectList(null);
        ArrayList<BookingTimesVo> bookingTimesVos = new ArrayList<>();
        appointments.forEach(item->{
            BookingTimesVo vo = new BookingTimesVo();
            vo.setDateTime(item.getAppointmenttime());
            bookingTimesVos.add(vo);
        });
        return bookingTimesVos;
    }

    @Override
    public List<RatingVo> rating() {
        List<Counselors> list = counselorsMapper.selectList(null);
        ArrayList<RatingVo> vos = new ArrayList<>();
        int count = 0; // 计数器

        for (Counselors item : list) {
            if (count >= 7) { // 如果已处理的数量达到7，就退出循环
                break;
            }
            Integer userid = item.getUserid();
            RatingVo ratingVo = new RatingVo();
            String realname = usersMapper.selectOne(new QueryWrapper<Users>().eq("userId", userid)).getRealname();
            ratingVo.setName(realname);

            QueryWrapper<Useranalytics> wrapper = new QueryWrapper<Useranalytics>().eq("userId", userid);
            if (useranalyticsMapper.exists(wrapper)) {
                Useranalytics useranalytics = useranalyticsMapper.selectOne(wrapper);
                BeanUtils.copyProperties(useranalytics, ratingVo);
            } else {
                ratingVo.setCompletedappointments(0);
                ratingVo.setCanceledappointments(0);
                ratingVo.setTotalappointments(0);
            }

            ratingVo.setAveragerating(item.getRating());
            vos.add(ratingVo);
            count++; // 增加计数器
        }

        return vos;

    }

    @Override
    public Boolean getAllRecord(Integer userid) {
        Integer counselorid = counselorsMapper.selectOne(new QueryWrapper<Counselors>().eq("userId", userid)).getCounselorid();
        return appointmentsMapper.exists(new QueryWrapper<Appointments>().eq("counselorId",counselorid).eq("status","scheduled"));
    }

    public static String formatTimeRange(Date startDate, Date endDate) {
        // 定义时间格式
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");

        // 格式化开始时间和结束时间
        String startTime = formatter.format(startDate);
        String endTime = formatter.format(endDate);

        // 返回拼接后的时间范围字符串
        return startTime + " - " + endTime;
    }

    // 分组方法
    private List<List<AppointmentVo>> groupList(List<AppointmentVo> list, int groupSize) {
        List<List<AppointmentVo>> result = new ArrayList<>();
        for (int i = 0; i < list.size(); i += groupSize) {
            int end = Math.min(i + groupSize, list.size());
            result.add(new ArrayList<>(list.subList(i, end)));
        }
        return result;
    }



}




